package com.ccom.test.serviceImpl;

import com.ccom.api.domain.Article;
import com.ccom.core.common.exception.CcomBootException;
import com.ccom.test.mapper.ArticleMapper;
import com.ccom.test.service.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Description:
 * @Author: zjj
 * @Date: 2021/12/22
 */
@Slf4j
@Service
public class TransactionServiceImpl implements TransactionService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addArticle(Long userId){
        log.info("start transaction...");
        saveArticle(userId);
        throw new CcomBootException("测试事务-带事务");
    }

    @Override
    public void addArticle1(Long userId){
        log.info("start no transaction...");
        saveArticle(userId);
        throw new CcomBootException("测试事务-不带事务");
    }

    // 不回滚(无rollbackFor,抛出Exception的子类也不回滚)
    @Transactional
    public void test1(Long userId) throws Exception {
        saveArticle(userId);
        throw new Exception("test1 error");
    }

    // 回滚（抛出Exception的子类也会回滚）
    @Transactional(rollbackFor = Exception.class)
    public void test2(Long userId) throws Exception {
        saveArticle(userId);
        throw new Exception("test2 error");
    }

    // 回滚
    @Transactional
    public void test3(Long userId) {
        saveArticle(userId);
        throw new RuntimeException("test3 runtime error");
    }

    // 回滚
    @Transactional(rollbackFor = Exception.class)
    public void test7(Long userId) throws Exception {
        saveArticle(userId);
    }

    public void saveArticle(Long userId){
        Article article = new Article();
        article.setCreateTime(new Date());
        article.setTitle("test transaction");
        article.setContent("test transaction");
        article.setUserId(userId);
        articleMapper.insert(article);
    }
}
